import os.path
from cgi import escape

import lxml.etree as et

from renyare.wsgi.error import RenyareError
from webob import Request

from renyare.xml import nsp as ren_nsp, ns_uri
from renyare.xml.xslt import skin_template
nsp = '{%s}'%ns_uri

class SkinMiddleware(object):
    def __init__(self, app, global_conf, app_conf, template=None):
        self.app = app
        self.global_conf = global_conf
        self.app_conf = app_conf
        print global_conf
        print app_conf

    def __call__(self, environ, start_response):
        skin = self.app_conf.get('skin', 'default')
        req = Request(environ)
        environ['skin'] = skin
        resp = req.get_response(self.app)
        return resp(environ, start_response)

class XsltTemplatePlugin(object):
    """A plugin to use XSLT transformations with Pylons framework. Works as Buffet plugin"""
    def __init__(self, extra_vars_func=None, options=None):
        pass
        # Store the two arguments (normally dicts of strings), and do any other initialization required.

    def load_template(self, templatename):
        pass
        # Optional: not called by Pylons.  Called by TurboGears in special circumstances; see Buffet interface for
        # details.

    def render(self, info, format="html", fragment=False, template=None):
        # Return a rendered version of the template.
        # 'info' is a dict of context variables (string : anything).
        # 'format' is the desired output format.  This is engine-specific.
        # 'fragment' is true if the template should be rendered "standalone"; i.e., bypassing any inherited templates
        #     or wrapper templates that would normally be applied.  The plugin may ignore this argument if the engine
        #     does not support this.
        # 'template' is the template name (string).  Buffet requires dotted notation (see below), while Pylons
        #     allows URI notation.
        # The method should call the 'extra_vars_funcs' function given to the constructor, and merge those
        # variables in with 'info'.
        if not hasattr(info['c'], 'xml') or info['c'].xml is None:
            raise RenyareError("No xml tree given in context variables")
        xml = info['c'].xml
        if info['config']['xsl'] == 'client':
            return et.tostring(xml)
        else:
            base_paths = info['config']['pylons.paths']['templates']
            if template is None:
                template = info['config']['default_template']
            skin = info['request'].environ['skin']
            real_template = skin_template(base_paths, skin, template, info['config']['xsl'])
            if real_template is None:
                raise RenyareError("No template '%s' found at any of template paths" % template)
            xsl = et.parse(file(real_template))
            transform = et.XSLT(xsl)
            return str(transform(xml))

    def transform(self, info, template):
        pass
        # Optional: not called by Pylons.  Called by TurboGears to render the template as a tree of ElementTree
        # nodes rather than as a string.  Kid is the only known engine that supports this.
